package com.okb.utils;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: hcxu
 * Time: 2024/11/21 2:05 PM
 */
@Slf4j
public abstract class WebSocketClientUtil extends WebSocketClient {
    private static final int MAX_RETRIES = 50; // 最大重试次数
    private static final int RETRY_DELAY_SECONDS = 1; // 每次重试的间隔，单位：秒
    private int retryCount = 0; // 当前重试次数

    public WebSocketClientUtil(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("连接已建立");
        onSubscribe();
    }

    /**
     * 由子类实现具体的订阅逻辑
     */
    protected abstract void onSubscribe();


    @Override
    public void onMessage(String message) {
        onMessageHandle(message);
    }

    /**
     * 由子类实现具体的消息处理逻辑
     */
    protected abstract void onMessageHandle(String message);

    @Override
    public void onClose(int i, String s, boolean b) {
        handleReconnect();
    }

    @Override
    public void onError(Exception e) {

    }

    // 重试机制：如果连接断开，则等待并重新连接
    private void handleReconnect() {
        if (retryCount < MAX_RETRIES) {
            retryCount++;
            log.info("准备重试连接，第 " + retryCount + " 次...");
            try {
                // 等待一段时间后重试
                TimeUnit.SECONDS.sleep(RETRY_DELAY_SECONDS);
                tryReConnect();  // 尝试重新连接
            } catch (InterruptedException e) {
                log.error("重试过程中发生错误", e);
            }
        } else {
            log.error("已达到最大重试次数，停止重试");
        }
    }

    // 尝试重新连接 WebSocket
    protected abstract void tryReConnect();

    public void startClient(){
        try {
            this.connectBlocking();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
